package com.sihuatech.coreagent.until;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.digester3.Digester;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import com.sihuatech.coreagent.controller.VasController;
import com.sihuatech.coreagent.model.request.ChargeNotificationRequest;
import com.sihuatech.coreagent.model.response.MPOrderNotifyReq;
import com.sihuatech.coreagent.model.response.MpItem;


public class XmlParser {
	
	private static final Logger logger = LoggerFactory.getLogger(XmlParser.class);
	
	public static String getXml(HttpServletRequest request){
		InputStream is;
		String xml = "";
		try {
			is = request.getInputStream();
			xml = IOUtils.toString(is, "UTF-8");
		} catch (IOException e) {
			logger.error("http IO问题", e);
		}
		return xml;
	}
	
	
	public static ChargeNotificationRequest getChargeNotificationRequest (String xml) {
		Digester digester = new Digester();
		digester.setValidating(false);
		digester.addObjectCreate("ChargeNotificationRequest", ChargeNotificationRequest.class);
		digester.addBeanPropertySetter("ChargeNotificationRequest/Body/ORDER_ID", "orderId");
		digester.addBeanPropertySetter("ChargeNotificationRequest/Body/TradeSession", "tradeSession");
		InputStream in = getInputStream(xml);
		try {
			return (ChargeNotificationRequest) digester.parse(in);
		} catch (IOException e) {
			logger.error("报文解析出错");
		} catch (SAXException e) {
			logger.error("报文解析出错");
		}
		return null;
	}
	
	public static MPOrderNotifyReq getMPOrderNotifyReq (String xml) {
		Digester digester = new Digester();
		digester.setValidating(false);
		digester.addObjectCreate("MPOrderNotifyReq", MPOrderNotifyReq.class);
		digester.addBeanPropertySetter("MPOrderNotifyReq/Body/NOTIFY_COUNT", "notifyCount");
		digester.addObjectCreate("MPOrderNotifyReq/Body/ITEM", MpItem.class);
		digester.addBeanPropertySetter("MPOrderNotifyReq/Body/ITEM/INDEX", "index");
		digester.addBeanPropertySetter("MPOrderNotifyReq/Body/ITEM/ORDER_ID", "orderId");
		digester.addSetNext("MPOrderNotifyReq/Body/ITEM", "addMpItem","com.onewaveinc.miguvas.datamodel.request.MpItem");
		InputStream in = getInputStream(xml);
		try {
			return (MPOrderNotifyReq) digester.parse(in);
		} catch (IOException e) {
			logger.error("报文解析出错");
		} catch (SAXException e) {
			logger.error("报文解析出错");
		}
		return null;
	}
	
	private static InputStream getInputStream(String xml) {
		InputStream in = null;
		try {
			in = new ByteArrayInputStream(xml.getBytes("UTF-8"));
		} catch (Exception e) {
			logger.error("字符串转化流异常", e);
		}
		return in;
	}
}
